package org.jeecg.modules.flowermater.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.modules.flower.entity.*;
import org.jeecg.modules.flower.service.IFlowerStorehouseService;
import org.jeecg.modules.flower.util.CommonUtil;
import org.jeecg.modules.flowermater.service.IFlowerMaterialBookService;
import org.jeecg.modules.flowerutil.PeriodUtils;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.def.TemplateExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.flowermater.entity.FlowerMaterialIn;
import org.jeecg.modules.flowermater.entity.FlowerMaterialInMain;
import org.jeecg.modules.flowermater.vo.FlowerMaterialInMainPage;
import org.jeecg.modules.flowermater.service.IFlowerMaterialInMainService;
import org.jeecg.modules.flowermater.service.IFlowerMaterialInService;
import org.jeecgframework.poi.excel.view.JeecgTemplateExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 采后物资入库主表
 * @Author: jeecg-boot
 * @Date:   2022-07-13
 * @Version: V1.0
 */
@Api(tags="采后物资入库主表")
@RestController
@RequestMapping("/flowermater/flowerMaterialInMain")
@Slf4j
public class FlowerMaterialInMainController {
	@Autowired
	private IFlowerMaterialInMainService flowerMaterialInMainService;
	@Autowired
	private IFlowerMaterialInService flowerMaterialInService;

	 @Autowired
	 private IFlowerStorehouseService flowerStorehouseService;
	 @Autowired
	 private ISysDictService sysDictService;
	 @Autowired
	 private ISysUserService sysUserService;
	 @Value("${yth.tempMaterExcelin}")
	 private  String tempExcelin;


	/**
	 * 分页列表查询
	 *
	 * @param flowerMaterialInMain
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "采后物资入库主表-分页列表查询")
	@ApiOperation(value="采后物资入库主表-分页列表查询", notes="采后物资入库主表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(FlowerMaterialInMain flowerMaterialInMain,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req,
								   @RequestParam(value = "sDate",defaultValue = "") String sDate ,
								   @RequestParam(value = "eDate",defaultValue = "") String eDate) {
//		QueryWrapper<FlowerMaterialInMain> queryWrapper = QueryGenerator.initQueryWrapper(flowerMaterialInMain, req.getParameterMap());
		QueryWrapper<FlowerMaterialInMain> queryWrapper = new QueryWrapper<>();
		Page<FlowerMaterialInMain> page = new Page<FlowerMaterialInMain>(pageNo, pageSize);
		queryWrapper.orderByDesc("in_time");
		queryWrapper.orderByDesc("create_time");
		if(StringUtils.isNotBlank(flowerMaterialInMain.getNo())){
			queryWrapper.like("no",flowerMaterialInMain.getNo());
		}
		if(StringUtils.isNotBlank(flowerMaterialInMain.getPeriod())){
			queryWrapper.eq("period",flowerMaterialInMain.getPeriod());
		}
		if(StringUtils.isNotBlank(flowerMaterialInMain.getName())){
			queryWrapper.like("name",flowerMaterialInMain.getName());
		}
		if(StringUtils.isNotBlank(flowerMaterialInMain.getType())){
			queryWrapper.eq("type",flowerMaterialInMain.getType());
		}
		if(StringUtils.isNotBlank(flowerMaterialInMain.getSupplier())){
			queryWrapper.like("supplier",flowerMaterialInMain.getSupplier());
		}
		if(StringUtils.isNotBlank(flowerMaterialInMain.getStorehouse())){
			queryWrapper.eq("storehouse",flowerMaterialInMain.getStorehouse());
		}
		if(StringUtils.isNotBlank(flowerMaterialInMain.getInPersonName())){
			queryWrapper.like("in_person_name",flowerMaterialInMain.getInPersonName());
		}
		if(flowerMaterialInMain.getState() != null){
			queryWrapper.eq("state",flowerMaterialInMain.getState());
		}

		if(StringUtils.isNotBlank(sDate)){
			queryWrapper.ge("in_time",sDate);
		}
		if(StringUtils.isNotBlank(eDate)){
			queryWrapper.le("in_time",eDate+" 23:59:59");
		}

		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
		queryWrapper.inSql("storehouse","select b.code from flower_storehouse b , flower_storehouse_detail c " +
				"where b.id = c.mainid  " +
				"and personid = '"+sysUser.getId()+"'");
//		queryWrapper.exists("select 1 from flower_storehouse b , flower_storehouse_detail c " +
//				"where b.id = c.mainid  and flower_material_in_main.storehouse = b.code " +
//				"and personid = '"+sysUser.getId()+"'");

		IPage<FlowerMaterialInMain> pageList = flowerMaterialInMainService.page(page, queryWrapper);
		return Result.ok(pageList);
	}

	/**
	 *   添加
	 *
	 * @param flowerMaterialInMainPage
	 * @return
	 */
	@AutoLog(value = "采后物资入库主表-添加")
	@ApiOperation(value="采后物资入库主表-添加", notes="采后物资入库主表-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody FlowerMaterialInMainPage flowerMaterialInMainPage) {
		FlowerMaterialInMain flowerMaterialInMain = new FlowerMaterialInMain();
		BeanUtils.copyProperties(flowerMaterialInMainPage, flowerMaterialInMain);

		//自动生成出库单号
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
		String dateNo = simpleDateFormat.format(new Date());
//		String refex = "MRK" + dateNo;
		String refex = "RK-CHWZ-" + dateNo;
		LambdaQueryWrapper<FlowerMaterialInMain> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.like(FlowerMaterialInMain::getNo, refex);
		lambdaQueryWrapper.orderByDesc(FlowerMaterialInMain::getNo);
		List<FlowerMaterialInMain> list = flowerMaterialInMainService.list(lambdaQueryWrapper);
		String oldNo = "";
		if (list.size() > 0) {
			oldNo = list.get(0).getNo();
		}
		String no1 = CommonUtil.getNo("RK-CHWZ-", oldNo, 3);
		flowerMaterialInMain.setNo(no1);

		String storehouse = flowerMaterialInMain.getStorehouse();
		if( StringUtils.isNotBlank(storehouse)){
			LambdaQueryWrapper<FlowerStorehouse> queryWrapper =new LambdaQueryWrapper<>();
			queryWrapper.eq(FlowerStorehouse::getCode,storehouse);
			FlowerStorehouse one = flowerStorehouseService.getOne(queryWrapper);
			String cost = one.getCost();
			flowerMaterialInMain.setCost(cost);
		}
		flowerMaterialInMainService.saveMain(flowerMaterialInMain, flowerMaterialInMainPage.getFlowerMaterialInList());
		return Result.ok("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param flowerMaterialInMainPage
	 * @return
	 */
	@AutoLog(value = "采后物资入库主表-编辑")
	@ApiOperation(value="采后物资入库主表-编辑", notes="采后物资入库主表-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody FlowerMaterialInMainPage flowerMaterialInMainPage) {
		FlowerMaterialInMain flowerMaterialInMain = new FlowerMaterialInMain();
		BeanUtils.copyProperties(flowerMaterialInMainPage, flowerMaterialInMain);
		FlowerMaterialInMain flowerMaterialInMainEntity = flowerMaterialInMainService.getById(flowerMaterialInMain.getId());
		if(flowerMaterialInMainEntity==null) {
			return Result.error("未找到对应数据");
		}

		String storehouse = flowerMaterialInMain.getStorehouse();
		if( StringUtils.isNotBlank(storehouse)){
			LambdaQueryWrapper<FlowerStorehouse> queryWrapper =new LambdaQueryWrapper<>();
			queryWrapper.eq(FlowerStorehouse::getCode,storehouse);
			FlowerStorehouse one = flowerStorehouseService.getOne(queryWrapper);
			String cost = one.getCost();
			flowerMaterialInMain.setCost(cost);
		}

		flowerMaterialInMainService.updateMain(flowerMaterialInMain, flowerMaterialInMainPage.getFlowerMaterialInList());
		return Result.ok("编辑成功!");
	}


	 /**
	  *  库管确认
	  *
	  * @param    flowerMaterialInMain
	  * @return
	  */
	 @AutoLog(value = "采后物资入库主表-库管确认")
	 @ApiOperation(value="采后物资入库主表-库管确认", notes="采后物资入库主表-库管确认")
	 @PutMapping(value = "/houseSure")
	 @Transactional
	 public Result<?> houseSure(@RequestBody  FlowerMaterialInMain flowerMaterialInMain) {
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();

		 FlowerMaterialInMain flowerMaterialInMainEntity = flowerMaterialInMainService.getById(flowerMaterialInMain.getId());
		 if(flowerMaterialInMainEntity==null) {
			 return Result.error("未找到对应数据");
		 }
		 if(flowerMaterialInMain.getState() != 0){
			if(flowerMaterialInMain.getState()==1){
				throw new RuntimeException("库管已经确认");
			}else if(flowerMaterialInMain.getState()==2){
				throw new RuntimeException("财务已经确认");
			}else
		 		throw new RuntimeException("不满足库管确认条件");
		 }

		 String id = flowerMaterialInMain.getId();
		 FlowerMaterialInMain flowerMaterialInMainNew = new FlowerMaterialInMain();
		 flowerMaterialInMainNew.setId(id);
		 flowerMaterialInMainNew.setHouseSureUser(sysUser.getRealname());
		 flowerMaterialInMainNew.setHouseSureTime(new Date());
		 flowerMaterialInMainNew.setState(1);
		 flowerMaterialInMainService.updateById(flowerMaterialInMainNew);

		 return Result.ok("库管确认成功!");
	 }
	 /**
	  *  取消库管确认
	  *
	  * @param    flowerMaterialInMain
	  * @return
	  */
	 @AutoLog(value = "采后物资入库主表-取消库管确认")
	 @ApiOperation(value="采后物资入库主表-取消库管确认--更新库存", notes="采后物资入库主表-取消库管确认")
	 @PutMapping(value = "/houseSureBack")
	 @Transactional
	 public Result<?> houseSureBack(@RequestBody FlowerMaterialInMain flowerMaterialInMain) {

		 FlowerMaterialInMain flowerMaterialInMainEntity = flowerMaterialInMainService.getById(flowerMaterialInMain.getId());
		 if(flowerMaterialInMainEntity==null) {
			 return Result.error("未找到对应数据");
		 }
		 if(flowerMaterialInMain.getState() != 1){
			 throw new RuntimeException("请库管进行先确认！才能取消！");
		 }

		 String id = flowerMaterialInMain.getId();
		 FlowerMaterialInMain flowerMaterialInMainNew = new FlowerMaterialInMain();
		 flowerMaterialInMainNew.setId(id);
		 flowerMaterialInMainNew.setHouseSureUser( "");
		 flowerMaterialInMainNew.setHouseSureTime(null);
		 flowerMaterialInMainNew.setState(0);
		 flowerMaterialInMainService.updateById(flowerMaterialInMainNew);

		 return Result.ok("库管取消确认成功!");
	 }
	 /**
	  *
	  * 财务复核
	  * @param flowerMaterialInMain
	  * @return
	  */
	 @AutoLog(value = "采后物资入库主表-财务复核")
	 @ApiOperation(value="采后物资入库主表-财务复核--更新财务确认人--更新库存", notes="采后物资入库主表-财务复核--更新财务确认人--更新库存")
	 @PutMapping(value = "/finaSure")
	 @Transactional
	 public Result<?> finaSure(@RequestBody FlowerMaterialInMain flowerMaterialInMain) {
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();

		 if(StringUtils.isBlank(flowerMaterialInMain.getHouseSureUser())){
		 	throw new RuntimeException("请库管进行先确认！财务才能复核！");
		 }
		 if(flowerMaterialInMain.getState() != 1){
			 throw new RuntimeException("请库管进行先确认！财务才能复核！");
		 }
		 if(StringUtils.isNotBlank(flowerMaterialInMain.getFinaSureUser())){
			 throw new RuntimeException("财务已经复核确认！请先取消");
		 }
		 String id = flowerMaterialInMain.getId();
		 FlowerMaterialInMain flowerMaterialInMainNew = new FlowerMaterialInMain();
		 flowerMaterialInMainNew.setId(id);
		 flowerMaterialInMainNew.setHouseSureTime( flowerMaterialInMain.getHouseSureTime());
		 flowerMaterialInMainNew.setFinaSureUser(sysUser.getRealname());
		 flowerMaterialInMainNew.setFinaSureTime(new Date());
		 flowerMaterialInMainNew.setState(2);
		 flowerMaterialInMainService.updateById(flowerMaterialInMainNew);

		 //增加库存
		 List<FlowerMaterialIn> flowerMaterialIns = flowerMaterialInService.selectByMainId(id);
		 flowerMaterialInMainService.updateBookSure(flowerMaterialInMain, flowerMaterialIns);
		 return Result.ok("财务复核成功!");
	 }
	 /**
	  *
	  * 取消财务复核
	  * @param flowerMaterialInMain
	  * @return
	  */
	 @AutoLog(value = "采后物资入库主表-取消财务复核")
	 @ApiOperation(value="采后物资入库主表-取消财务复核--更新财务确认人", notes="采后物资入库主表-取消财务复核--更新财务确认人")
	 @PutMapping(value = "/finaSureBack")
	 @Transactional
	 public Result<?> finaSureBack(@RequestBody FlowerMaterialInMain flowerMaterialInMain) {
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();

		 if(StringUtils.isBlank(flowerMaterialInMain.getHouseSureUser())){
			 throw new RuntimeException("请库管进行先确认！财务才能复核！");
		 }
		 if(flowerMaterialInMain.getState() != 2){
			 throw new RuntimeException("请财务进行先复核确认！才能取消！");
		 }
		 if(StringUtils.isBlank(flowerMaterialInMain.getFinaSureUser())){
			 throw new RuntimeException("请财务进行先复核确认！才能取消！");
		 }
		 String id = flowerMaterialInMain.getId();
		 FlowerMaterialInMain flowerMaterialInMainNew = new FlowerMaterialInMain();
		 flowerMaterialInMainNew.setId(id);
		 flowerMaterialInMainNew.setFinaSureUser( "");
		 flowerMaterialInMainNew.setFinaSureTime( null);
		 flowerMaterialInMainNew.setHouseSureTime( flowerMaterialInMain.getHouseSureTime());
		 flowerMaterialInMainNew.setState(1);
		 flowerMaterialInMainService.updateById(flowerMaterialInMainNew);
		 //归还库存
		 flowerMaterialInMainService.updateBookSureBack(flowerMaterialInMain);
		 return Result.ok("取消财务复核成功!");
	 }

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "采后物资入库主表-通过id删除")
	@ApiOperation(value="采后物资入库主表-通过id删除", notes="采后物资入库主表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		flowerMaterialInMainService.delMain(id);
		return Result.ok("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "采后物资入库主表-批量删除")
	@ApiOperation(value="采后物资入库主表-批量删除", notes="采后物资入库主表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.flowerMaterialInMainService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功！");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "采后物资入库主表-通过id查询")
	@ApiOperation(value="采后物资入库主表-通过id查询", notes="采后物资入库主表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		FlowerMaterialInMain flowerMaterialInMain = flowerMaterialInMainService.getById(id);
		if(flowerMaterialInMain==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(flowerMaterialInMain);

	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "采后物资入库子表通过主表ID查询")
	@ApiOperation(value="采后物资入库子表主表ID查询", notes="采后物资入库子表-通主表ID查询")
	@GetMapping(value = "/queryFlowerMaterialInByMainId")
	public Result<?> queryFlowerMaterialInListByMainId(@RequestParam(name="id",required=true) String id) {
		List<FlowerMaterialIn> flowerMaterialInList = flowerMaterialInService.selectByMainId(id);
		return Result.ok(flowerMaterialInList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param flowerMaterialInMain
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, FlowerMaterialInMain flowerMaterialInMain,
								  @RequestParam(value = "sDate",defaultValue = "") String sDate ,
								  @RequestParam(value = "eDate",defaultValue = "") String eDate) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<FlowerMaterialInMain> queryWrapper = QueryGenerator.initQueryWrapper(flowerMaterialInMain, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		queryWrapper.orderByAsc("in_time");
		queryWrapper.orderByAsc("create_time");
		if(StringUtils.isNotBlank(sDate)){
			queryWrapper.ge("in_time",sDate);
		}
		if(StringUtils.isNotBlank(eDate)){
			queryWrapper.le("in_time",eDate+" 23:59:59");
		}
      //Step.2 获取导出数据
      List<FlowerMaterialInMain> queryList = flowerMaterialInMainService.list(queryWrapper);
      // 过滤选中数据
      String selections = request.getParameter("selections");
      List<FlowerMaterialInMain> flowerMaterialInMainList = new ArrayList<FlowerMaterialInMain>();
      if(oConvertUtils.isEmpty(selections)) {
          flowerMaterialInMainList = queryList;
      }else {
          List<String> selectionList = Arrays.asList(selections.split(","));
          flowerMaterialInMainList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
      }

      // Step.3 组装pageList
      List<FlowerMaterialInMainPage> pageList = new ArrayList<FlowerMaterialInMainPage>();
      for (FlowerMaterialInMain main : flowerMaterialInMainList) {
          FlowerMaterialInMainPage vo = new FlowerMaterialInMainPage();
          BeanUtils.copyProperties(main, vo);
          List<FlowerMaterialIn> flowerMaterialInList = flowerMaterialInService.selectByMainId(main.getId());
          vo.setFlowerMaterialInList(flowerMaterialInList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "采后物资入库主表列表");
      mv.addObject(NormalExcelConstants.CLASS, FlowerMaterialInMainPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("采后物资入库主表数据", "导出人:"+sysUser.getRealname(), "采后物资入库主表"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<FlowerMaterialInMainPage> list = ExcelImportUtil.importExcel(file.getInputStream(), FlowerMaterialInMainPage.class, params);
              for (FlowerMaterialInMainPage page : list) {
                  FlowerMaterialInMain po = new FlowerMaterialInMain();
                  BeanUtils.copyProperties(page, po);
                  flowerMaterialInMainService.saveMain(po, page.getFlowerMaterialInList());
              }
              return Result.ok("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.ok("文件导入失败！");
    }


	 /**
	  *
	  * 导出excel入库单
	  *
	  * @param request
	  * @param flowerMaterialInMain
	  * @return
	  */
	 @RequestMapping(value = "/exportXlsForTemp")
	 @ApiOperation(value="导出excel入库单-导出excel入库单", notes="导出excel入库单-导出excel入库单")
	 public ModelAndView exportXlsForTemp(HttpServletRequest request,   FlowerMaterialInMain flowerMaterialInMain) {
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 SimpleDateFormat simpleDateFormat =new SimpleDateFormat("yyyy/MM/dd");
		 if(StringUtils.isBlank(tempExcelin)){
			 throw new RuntimeException("还未配置入库单模板，请联系管理员配置入库单模板");
		 }
		 TemplateExportParams params   = new TemplateExportParams(tempExcelin);//模板

		 String id = flowerMaterialInMain.getId();
		 FlowerMaterialInMain inMain = flowerMaterialInMainService.getById(id);

		 String cost = inMain.getCost();
		 String storehouse2 = inMain.getStorehouse();
		 String storehouseName = "";
		 String costName = "";
		 if(StringUtils.isNotBlank(cost)  ){
			 String name = sysDictService.queryDictTextByKey("ch_cost", cost);
			 costName = name ;
		 }
		 if( StringUtils.isNotBlank(storehouse2) ){
			 QueryWrapper<FlowerStorehouse> queryWrapper2=new QueryWrapper<>();
			 queryWrapper2.eq("code", storehouse2 );
			 FlowerStorehouse house = flowerStorehouseService.getOne(queryWrapper2);
			 storehouseName = house.getName();
		 }
		 String no="";
		 if(StringUtils.isNotBlank(inMain.getNo())){
			 no = inMain.getNo() ;
		 }
//		 String sourceGreenhouse = "";
//		 if(StringUtils.isNotBlank(tagInMain2.getSourceGreenhouse()) ){
//			 FlowerPlantingGreenhouse greenhouse = greenhouseService.getById(tagInMain2.getSourceGreenhouse());
//			 sourceGreenhouse  = greenhouse.getName();
//		 }

		 Map<String, Object> map = new HashMap<String, Object>();
		 map.put("sortTime", simpleDateFormat.format(inMain.getInTime()));
		 map.put("cost", costName);
		 map.put("storehouse", storehouseName);
		 map.put("no", no);

		 map.put("houseSureUser", inMain.getHouseSureUser());
		 SysUser user = sysUserService.getUserByName(inMain.getCreateBy());
		 map.put("createby", user.getRealname());

		 List<FlowerMaterialIn> indetalList = flowerMaterialInService.selectByMainId(id);

		 if(indetalList.size()==0){
			 throw new RuntimeException("没有入库详情不能生成入库单");
		 }
		 List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>();
		 BigDecimal countPrice =new BigDecimal("0");
		 Double countNum = Double.parseDouble("0");

		 for(FlowerMaterialIn materialIn : indetalList){
			 Map<String, Object> lm = new HashMap<String, Object>();

			 lm.put("supplier", materialIn.getSupplier() );
			 lm.put("name", materialIn.getName() );
			 lm.put("code", materialIn.getCode() );
			 lm.put("specs", materialIn.getSpecs() );
			 lm.put("unitMeasure", materialIn.getUnitMeasure() );
			 lm.put("price", materialIn.getPrice() );
			 BigDecimal totalPrice =new BigDecimal("0");
			 Double num = Double.parseDouble("0");
			 if(materialIn.getTotalPrice()!=null){
				 totalPrice = materialIn.getTotalPrice() ;
			 }
			 if(materialIn.getNum()!=null){
				 num = materialIn.getNum() ;
			 }
			 lm.put("num", num );
			 lm.put("totalPrice", totalPrice );

			 countNum += num ;//计算数量合计
			 countPrice = countPrice.add(totalPrice);
			 listMap.add(lm);
		 }
		 if(indetalList.size()==1){
			 Map<String, Object> lm = new HashMap<String, Object>();
			 listMap.add(lm);
		 }
		 map.put("sumNumber",countNum);
		 map.put("sumtotalPrice",countPrice);
		 map.put("maplist", listMap);

		 ModelAndView mv2 = new ModelAndView(new JeecgTemplateExcelView());
		 mv2.addObject(TemplateExcelConstants.PARAMS,params);
		 mv2.addObject(TemplateExcelConstants.MAP_DATA,map);
		 return mv2;
	 }



 }
